package project.dade.cn.bst.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.squareup.okhttp.Request;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildCheckedChangeListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import project.dade.cn.bst.R;
import project.dade.cn.bst.activity.GoshoppingActivity;
import project.dade.cn.bst.activity.SubmitOrder;
import project.dade.cn.bst.adapter.base.ShoppingAdapter;
import project.dade.cn.bst.adapter.base.ShoppingCartBean;
import project.dade.cn.bst.base.ParentFragment;
import project.dade.cn.bst.base.ZJPbaseFragment;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.ShopModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;

/**
 * Created by vain zhou on 2015/9/25.
 */
public class ShoppingFragment extends ParentFragment implements View.OnClickListener, BGAOnRVItemClickListener, BGAOnItemChildClickListener, BGAOnItemChildCheckedChangeListener {

    public static String FRAGMENT_TAG = ShoppingFragment.class.getSimpleName();
    @InjectView(R.id.error_layout)
    EmptyLayout emptyLayout;
    @InjectView(R.id.rv_recyclerview_data)
    RecyclerView recyclerView;
    private ShoppingAdapter shoppingAdapter;
    public RelativeLayout shopcart_layout_view_compute; // 结算内容
    public RelativeLayout shopcart_layout_view_nodata; // 无数据内容
    @InjectView(R.id.shopcart_layout_view_goShop)
    Button goshop;
    @InjectView(R.id.shopcart_layout_view_compute)
    public RelativeLayout shopcart_layout_content;
    private List<ShopModel> mList = new ArrayList<ShopModel>();
    @InjectView(R.id.cbCheckBox)
    CheckBox cbCheckBox;
    @InjectView(R.id.shoppingcart_sum)
    public TextView shoppingcart_sum; // 合计值
    @InjectView(R.id.shoppingcart_num)
    Button shoppingcart;
    private KProgressHUD hud;

    @Override
    public int setRootViewID() {
        return 0;
    }

    @Override
    public void findView(View rootView) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_shop, null);
        ButterKnife.inject(this, v);
        shopcart_layout_view_compute = (RelativeLayout) v.findViewById(R.id.shopcart_layout_content);
        shopcart_layout_view_nodata = (RelativeLayout) v.findViewById(R.id.shopcart_layout_view_nodata);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        shoppingAdapter = new ShoppingAdapter(recyclerView);
        shoppingAdapter.setOnRVItemClickListener(this);
        recyclerView.setAdapter(shoppingAdapter);
        shoppingAdapter.setOnRVItemClickListener(this);
        shoppingAdapter.setOnItemChildClickListener(this);
        shoppingAdapter.setOnItemChildCheckedChangeListener(this);
        goshop.setOnClickListener(this);
        shoppingcart.setOnClickListener(this);
        cbCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseAll(cbCheckBox.isChecked());
                setCount();
                Log.i(TAG, "-----chooseAll");
            }
        });
        return v;

    }


    @Override
    public void onResume() {
        super.onResume();

        initRequest();
    }

    @Override
    public void onPause() {
        super.onPause();
    }



    private void initRequest() {
        if (AppUtil.isNetworkAvailable(getActivity())) {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            requestGetShop();

        } else {
            Snackbar.make(getView(),"网络不通", Snackbar.LENGTH_SHORT).show();

        }

    }

    private void requestGetShop() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Shopping).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                       emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        Snackbar.make(getView(),"网络连接失败,请稍后在试", Snackbar.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        LogUtil.i(TAG, "购物车商品：" + response);
                        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                        LogUtil.i(TAG, "购物车商品：" + model.getData());
                        if (model != null && model.getResult() == 0 || model.getResult() == 1) {
                            initAdpter(response);

                        } else {
                            emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                            ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "获取购物车"));

                        }
                    }

                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shopcart_layout_view_goShop:
                redirectToPage(GoshoppingActivity.class);
                break;
            case R.id.shoppingcart_num:
                redirectToOrderCenter();

                break;
        }


    }

    @Override
    public void onRVItemClick(ViewGroup viewGroup, View view, int i) {


    }

    @Override
    public void onItemChildClick(ViewGroup viewGroup, View childView, final int position) {
        if (childView.getId() == R.id.delete) {

            if (AppUtil.isNetworkAvailable(getActivity())) {
                new MaterialDialog.Builder(getActivity())
                        .title(R.string.tips_title)
                        .titleColor(getResources().getColor(R.color.background_material_dark))
                        .theme(Theme.LIGHT)
                        .content(R.string.tips_shopping_delete)
                        .positiveText(R.string.ok)
                        .negativeText(R.string.cancel)
                        .callback(new MaterialDialog.ButtonCallback() {
                            @Override
                            public void onPositive(MaterialDialog dialog) {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
                params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile().toString());
                params.put("ProductId", shoppingAdapter.getItem(position).getProductId());
                params.put("Id", shoppingAdapter.getItem(position).getId());
                params.put("Quantity", shoppingAdapter.getItem(position).getQuantity());
                params.put("Sign", FormatRequest.main(params));
                new OkHttpRequest.Builder()
                        .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Shoppingcar).params(params)
                        .post(new ResultCallback<String>() {
                            @Override
                            public void onError(Request request, Exception e) {

                                ToastUtil.showShort(getActivity(), "网络相应失败请稍后再试");
                            }

                            @Override
                            protected void finalize() throws Throwable {
                                super.finalize();
                            }

                            @Override
                            public void onResponse(String response) {
                                LogUtil.i(TAG, "删除商品商品：" + response);
                                BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                                if (model != null && model.getResult() == 0) {
                                    shoppingAdapter.removeItem(position);
                                    shoppingAdapter.notifyDataSetChanged();
                                    setCount();
                                    if (shoppingAdapter.getDatas().size() == 0) {
                                        recyclerView.setVisibility(View.GONE);
                                        shopcart_layout_view_nodata.setVisibility(View.VISIBLE);
                                        shopcart_layout_content.setVisibility(View.GONE);

                                    }
                                } else {
                                    ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "删除商品"));
                                }


                            }

                        });
                            }

                        }).show();


            } else {
                Snackbar.make(getView(),"网络不通", Snackbar.LENGTH_SHORT).show();
            }
        }else if(childView.getId() == R.id.sub) {
            if (Integer.valueOf(mList.get(position).getQuantity()) <= 1) {
                Snackbar.make(getView(),"商品不能再减少了哦", Snackbar.LENGTH_SHORT).show();

            } else {
                if (AppUtil.isNetworkAvailable(getActivity())) {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
                    params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile().toString());
                    params.put("Id", shoppingAdapter.getItem(position).getId());
                    params.put("Sign", FormatRequest.main(params));
                    new OkHttpRequest.Builder()
                            .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.sub).params(params)
                            .post(new ResultCallback<String>() {
                                @Override
                                public void onError(Request request, Exception e) {

                                    ToastUtil.showShort(getActivity(), "网络相应失败请稍后再试");
                                }

                                @Override
                                public void onResponse(String response) {
                                    LogUtil.i(TAG, "减少数量：" + response);
                                    BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                                    if (model != null && model.getResult() == 0) {
                                        mList.get(position).setQuantity(String.valueOf(Integer.valueOf(mList.get(
                                                position).getQuantity()) - 1));
                                        shoppingAdapter.notifyDataSetChanged();
                                        setCount();
                                    } else {

                                        ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "删除商品"));
                                    }


                                }


                            });


                }
            }

            }else if (childView.getId() == R.id.add) {
            if (AppUtil.isNetworkAvailable(getActivity())) {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
                params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile().toString());
                params.put("Id", shoppingAdapter.getItem(position).getId());
                params.put("Sign", FormatRequest.main(params));
                new OkHttpRequest.Builder()
                        .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.add).params(params)
                        .post(new ResultCallback<String>() {
                            @Override
                            public void onError(Request request, Exception e) {

                                ToastUtil.showShort(getActivity(), "网络相应失败请稍后再试");
                            }

                            @Override
                            public void onResponse(String response) {
                                LogUtil.i(TAG, "添加数量：" + response);
                                BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                                if (model != null && model.getResult() == 0) {
                                    mList.get(position).setQuantity(String.valueOf(Integer.valueOf(mList.get(
                                            position).getQuantity()) + 1));
                                    shoppingAdapter.notifyDataSetChanged();
                                    setCount();

                                } else {

                                    ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "添加商品"));
                                }


                            }

                        });


            }

        }


    }

    /**
     * 跳转相关页功能
     *
     * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {

        startActivity(new Intent(getActivity(), class1));

    }

    @Override
    public void onItemChildCheckedChanged(ViewGroup parent, CompoundButton childView, int position, boolean isChecked) {
        shoppingAdapter.getItem(position).isChecked = isChecked;
        boolean isAllSelceted = true;
        for (ShopModel item : mList) {
            if (!item.isChecked) {
                isAllSelceted = false;
                break;
            }
        }
        cbCheckBox.setChecked(isAllSelceted);
        setCount();
    }
    /**
     * 跳转到结算中心
     */
    private void redirectToOrderCenter() {
        StringBuffer cartIds = new StringBuffer("");
        if (mList != null && mList.size() > 0) {
            ArrayList<ShopModel> items = new ArrayList<ShopModel>();
            for(ShopModel shopModel :mList) {
                ShopModel item = new ShopModel();
                if (shopModel != null && shopModel.isChecked == true) {
                    item.setQuantity(shopModel.getQuantity());
                    item.setPrice(shopModel.getPrice());
                    item.setId(shopModel.getId());
                    item.setPrice(shopModel.getPrice());
                    item.setProductImage(shopModel.getProductImage());
                    item.setProductName(shopModel.getProductName());
                    items.add(item);
                }

            }
               LogUtil.i(TAG, "改造后的数据数量为:" + (items != null ? items.size() : 0));
                for (ShopModel shopitem : items) {
                 LogUtil.i(TAG, "改造后的数据为：" + shopitem.getProductName()
                         + ",产品数量：" + shopitem.getQuantity() + ",产品价格："
                         + shopitem.getPrice());
                }
                if(items.size()>0){
                    ShoppingCartBean bean = new ShoppingCartBean();
                    bean.setProductList(items);
                    Intent intent = new Intent(getActivity(),
                            SubmitOrder.class);
                    Bundle data=new Bundle();
                    data.putSerializable("data", bean);
                    data.putString("type","0");
                    intent.putExtras(data);
                    startActivity(intent);

                }else {
                    new MaterialDialog.Builder(getActivity())
                            .title(R.string.tips_title)
                            .titleColor(getResources().getColor(R.color.background_material_dark))
                            .theme(Theme.LIGHT)
                            .content("请至少购买一件商品呦")
                            .positiveText(R.string.ok)
                            .callback(new MaterialDialog.ButtonCallback() {

                            }).show();
                }

        }else {
            new MaterialDialog.Builder(getActivity())
            .title(R.string.tips_title)
                    .titleColor(getResources().getColor(R.color.background_material_dark))
                    .theme(Theme.LIGHT)
                    .content("购物车数据异常")
                    .positiveText(R.string.ok)
                    .callback(new MaterialDialog.ButtonCallback() {
                    }).show();
            LogUtil.i(TAG, "购物车数据为空，不能结算");
        }
    }

    /**
     * 点击全选
     *
     * @param is_choose_all
     */
    private void chooseAll(boolean is_choose_all) {
        for (ShopModel item : mList) {

            item.isChecked = is_choose_all;
        }

        shoppingAdapter.notifyDataSetChanged();


    }

    private void initAdpter(String response) {
        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
        LogUtil.i(TAG, "购物车商品：" + model.getData());
        if(model.getResult() == 1){
            LogUtil.i(TAG, "购物车商品数量：" + mList.size());
            recyclerView.setVisibility(View.GONE);
            shopcart_layout_view_nodata.setVisibility(View.VISIBLE);
            shopcart_layout_content.setVisibility(View.GONE);

        }else {
            recyclerView.setVisibility(View.VISIBLE);
            shopcart_layout_view_nodata.setVisibility(View.GONE);
            shopcart_layout_content.setVisibility(View.VISIBLE);
            mList = JSON.parseArray(model.getData(), ShopModel.class);
            LogUtil.i(TAG, "购物车商品：" + mList);
            shoppingAdapter.setDatas(mList);
            setCount();
        }
    }
    private void setCount(){
        double count = 0;
        for (ShopModel item : mList) {
            if(item.isChecked) {
                count = count + item.getTotalMoney();
            }
        }
        Log.i(TAG, "-----count = " + count);
        DecimalFormat df = new DecimalFormat("######0.00");
        shoppingcart_sum.setText("¥" + df.format(count));
    }



}

